<template>
  <a-modal @cancel="close" title="添加用户缴费" width="70vw" v-model:visible="visible" unmount-on-close>
    <div class="flex page-container fee-pane-content">
      <div class="relative flex-1 fee-list">
        <page-form :model="feeForm" ref="feeFormRef" layout="vertical" v-if="feeForm.orderFee.length > 0">
          <template v-for="(item, index) in feeForm.orderFee" :key="index">
            <div class="order-fee-item">
              <div class="flex justify-between order-fee-item-header">
                <div class="order-fee-item-header-text">费用名称<span class="required">*</span></div>
                <div class="flex items-center justify-center order-fee-item-header-close" @click="delFeeFn(index)"><icon-close /></div>
              </div>
              <div class="order-fee-item-content" style="position: relative">
                <!-- 已完成状态不允许添加线上费用 -->
                <!-- 线下订单不允许添加线上费用 -->
                <fee-pane
                  :orderFeeIndex="index"
                  :showStatistic="false"
                  :showFeeItemTitle="false"
                  :disabledOnlineFee="!orderInfo.canAddOnlineFee"
                >
                  <template #fee-pane-header>
                    <a-select
                      popup-container=".order-fee-item-content"
                      placeholder="请选择"
                      style="width: 280px"
                      v-model="item.feeDetailType"
                      @change="(val) => changeFeeTypeFn(val, item)"
                    >
                      <a-option
                        v-for="orderFeeCategory in orderFeeCategoryEnum"
                        :key="orderFeeCategory.value"
                        :value="orderFeeCategory.value"
                        :label="orderFeeCategory.label"
                      />
                    </a-select>
                  </template>
                </fee-pane>
              </div>
            </div>
          </template>
          <a-button type="primary" @click="addFeeFn">
            <template #icon>
              <icon-plus />
            </template>
            添加费用
          </a-button>
        </page-form>
        <list-empty v-else descriptions="暂无费用信息" btnText="添加费用" @add="addFeeFn" />
      </div>
      <div class="fee-statistic">
        <fee-statistic />
      </div>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="close">关闭</a-button>
        <a-button type="primary" :loading="okLoading" @click="submitFn">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <!-- 底部 footer -->
  <!-- <page-form-footer :ok-loading="okLoading" @ok="submitFn" /> -->
</template>

<script setup name="addFeesModal">
  import { ref, computed, provide } from 'vue'
  import { useRoute } from 'vue-router'
  import feePane from './order-fee/fee-pane.vue'
  import feeStatistic from './order-fee/fee-statistic.vue'
  import { getShortOrdrDetails } from '@/api/order/sOrder'
  import { getLongOrderDetails } from '@/api/order/czsOrder'
  import { addShortOrderCost, addLongOrderCost } from '@/api/business/workorder'
  import { Message } from '@arco-design/web-vue'
  import { buildCostInfoParam, getStoreTemplateDetail, compileFeeItemFromTemplate, initFeeDetail } from './order-fee/fee-utils.js'
  import { cloneDeep } from 'lodash-es'
  import useNavigate from '@/hooks/useNavigate'
  const emit = defineEmits(['ok'])
  const { navigateBack } = useNavigate()
  const route = useRoute()
  const visible = ref(false)
  const orderInfo = ref({})
  const orderId = ref(null)
  const workOrderId = ref(null)
  const orderType = ref(null)
  const orderFeeCategoryEnum = computed(() => {
    let orderInfoVal = orderInfo.value
    if (orderInfoVal) {
      let orderStatus = orderInfoVal.orderStatus
      console.log(orderStatus)
      let allList = [
        { label: '增值服务费', value: 'addServiceFee', feeNameId: 8 },
        { label: '优惠费', value: 'preferentialFee', feeNameId: 11 },
        { label: '其他费用', value: 'otherFee', feeNameId: 4 },
        // { label: '额外费用', value: 'extraFee', feeNameId: 3 },
        { label: '退款', value: 'refuseFee', feeNameId: 5 },
      ]
      // 已还车、已完成、已取消 可添加额外费用
      if ([300, 1000, -100].includes(orderStatus)) {
        allList.splice(2, 0, { label: '额外费用', value: 'extraFee', feeNameId: 3 })
      }
      // 已取消仅可添加额外费用
      if ([-100].includes(orderStatus)) {
        allList = [{ label: '额外费用', value: 'extraFee', feeNameId: 3 }]
      }
      // 待用车、用车中、已还车、已完成、已取消
      if ([100, 200, 300, 1000, -100].includes(orderStatus)) {
        allList.push({ label: '赔款', value: 'compensateFee', feeNameId: 17 })
      }
      return allList
    } else {
      return []
    }
  })
  // 费用相关 开始
  const feeFormRef = ref()
  const feeForm = ref({
    id: orderId.value,
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        readTemplate: true,
        feeDetailType: undefined,
        feeDetailList: [],
        feeDetailTypeList: [],
      },
    ],
  })
  const init = () => {
    feeForm.value = {
      id: orderId.value,
      randomKey: 0,
      orderFee: [
        {
          // 费用类型（线上费用|线下费用）
          feeType: 1,
          readTemplate: true,
          feeDetailType: undefined,
          feeDetailList: [],
          feeDetailTypeList: [],
        },
      ],
    }
  }
  provide('feeForm', feeForm)
  // 添加费用
  const addFeeFn = () => {
    feeForm.value.orderFee.push({
      // 费用类型（线上费用|线下费用）
      feeType: 1,
      readTemplate: true,
      feeDetailType: undefined,
      feeDetailList: [],
      feeDetailTypeList: [],
    })
  }
  // 删除费用
  const delFeeFn = (index) => {
    feeForm.value.orderFee.splice(index, 1)
  }
  // 门店模板信息
  const storeTemplate = ref()
  // 短租模板Id
  const priceTemplateId = ref()
  // 读取短租订单信息
  const getShortOrderDetail = () => {
    getShortOrdrDetails({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      getStoreTemplateDetail(orderInfo.value.siteId, 1, (template, templateId) => {
        storeTemplate.value = template
        priceTemplateId.value = templateId
        // 如果在未读取成功前，进行了 addFeeFn 及 changeFeeTypeFn 操作，需要补一下数据
        let orderFee = feeForm.value.orderFee
        if (orderFee && orderFee.length > 0) {
          if (orderFee.some((item) => item.feeDetailTypeList.length > 0)) {
            initFeeDetail(feeForm.value, storeTemplate.value)
          }
        }
      })
    })
  }
  // 读取长租订单信息
  const getLongOrderDetail = () => {
    getLongOrderDetails({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      getStoreTemplateDetail(orderInfo.value.siteId, 2, (template, templateId) => {
        storeTemplate.value = template
        priceTemplateId.value = templateId
        // 如果在未读取成功前，进行了 addFeeFn 及 changeFeeTypeFn 操作，需要补一下数据
        let orderFee = feeForm.value.orderFee
        if (orderFee && orderFee.length > 0) {
          if (orderFee.some((item) => item.feeDetailTypeList.length > 0)) {
            initFeeDetail(feeForm.value, storeTemplate.value)
          }
        }
      })
    })
  }
  // 获取门店配置开始
  const changeFeeTypeFn = (val, item) => {
    item.feeDetailTypeList = [val]
    // 读取门店模板信息成功
    if (storeTemplate.value) {
      item.priceTemplateId = priceTemplateId.value
      let option = orderFeeCategoryEnum.value.find((orderFeeItem) => orderFeeItem.value == item.feeDetailType)
      item.feeNameId = option.feeNameId
      compileFeeItemFromTemplate(item, storeTemplate.value)
    }
  }
  // 对 orderFee 进行二次处理
  const handleOrderFee = (orderFee) => {
    let tempOrderFee = cloneDeep(orderFee)
    tempOrderFee.forEach((feeItem) => {
      let temp = []
      let feeDetailList = feeItem.feeDetailList
      let remark
      feeDetailList.forEach((feeDetailItem) => {
        let childrenList = feeDetailItem.childrenList
        childrenList.forEach((item) => {
          let tempObj = {
            feeCategory: feeDetailItem.feeCategory,
            type: 1,
            ...item,
          }
          if (feeDetailItem.compensateReason) {
            tempObj.compensateReason = feeDetailItem.compensateReason
          }
          temp.push(tempObj)
          remark = feeDetailItem.remark
        })
      })
      feeItem.remark = remark
      feeItem.feeDetailList = temp
    })
    return tempOrderFee
  }
  // 提交
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    console.log('feeForm.value', feeForm.value)
    let feeFormValue = feeForm.value
    let { orderFee } = buildCostInfoParam(feeFormValue)
    const param = {
      id: orderId.value,
      workOrderId: workOrderId.value,
      orderFeeList: handleOrderFee(orderFee),
    }
    let orderFeeList = param.orderFeeList
    if (orderFeeList.length == 0) {
      Message.error('请添加费用')
      return
    } else {
      let hasError = false
      for (let i = 0; i < orderFeeList.length; i++) {
        let item = orderFeeList[i]
        if (!item.feeNameId) {
          hasError = true
          break
        }
      }
      if (hasError) {
        Message.error('请选择费用名称')
        return
      }
    }
    okLoading.value = true

    if (orderType.value == 1) {
      addShortOrderCost(param)
        .then((res) => {
          console.log(res)
          Message.success(res.message)
          close()
          emit('ok')
        })
        .finally(() => {
          okLoading.value = false
        })
    } else {
      addLongOrderCost(param)
        .then((res) => {
          console.log(res)
          Message.success(res.message)
          close()
          emit('ok')
        })
        .finally(() => {
          okLoading.value = false
        })
    }
  }

  const open = (record) => {
    init()
    visible.value = true
    orderId.value = record.refId
    workOrderId.value = record.id
    orderType.value = record.refType

    if (record.refType == 1) {
      record.refType = 1
      getShortOrderDetail()
    } else {
      record.refType = 2
      getLongOrderDetail()
    }
  }
  // 关闭
  const close = () => {
    visible.value = false
  }
  defineExpose({
    open,
  })
</script>
<style lang="less" scoped>
  .page-container {
    max-height: 70vh;
  }
  .fee-pane-content {
    width: 100%;
    .fee-statistic {
      width: 420px;
      margin-left: 20px;
    }
  }
  :deep(.arco-card) {
    background-color: inherit;
  }
  .order-fee-item {
    border-radius: 2px;
    border: 1px solid #e5e8ef;
    padding: 16px;
    margin-bottom: 20px;
    .order-fee-item-header {
      margin-bottom: 4px;
      .order-fee-item-header-text {
        font-size: 14px;
        color: #1d2129;
        line-height: 22px;
      }
      .order-fee-item-header-close {
        width: 16px;
        height: 16px;
        line-height: 16px;
        text-align: center;
        background: #f2f2f2;
        border-radius: 2px;
        cursor: pointer;
        svg {
          font-size: 12px;
        }
      }
    }
  }
  .required {
    width: 10px;
    height: 10px;
    font-size: 20px;
    color: #f53f3f;
    margin-left: 4px;
    line-height: 1;
    vertical-align: middle;
  }
</style>
